package com.bocai.dahuatech.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.IndividualBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseActivity;
import com.bocai.dahuatech.event.MainEvent;
import com.bocai.dahuatech.utils.BitmapUtil;
import com.bocai.dahuatech.utils.SharePrefencesUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 经销商注册第一步
 */
public class RegistDistributorThirdActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.iv_businesslicence_add)
    ImageView iv_businesslicence_add;
    @Bind(R.id.iv_identification_add)
    ImageView iv_identificationAdd;
    @Bind(R.id.iv_tax_add)
    ImageView iv_taxAdd;
    @Bind(R.id.iv_organizationcode_add)
    ImageView iv_organizationcodeAdd;
    ArrayList<String> photos=new ArrayList<>();
    private String businesslicence;
    private String identification;
    private String tax;
    private String organizationcode;
    private String photo;
    private int what;
    private IndividualBean bean;
    private String isregist;
    @Override
    protected int contentView() {
        return R.layout.activity_regist_distributor_third;
    }
    @Override
    protected void initView()
    {
        ButterKnife.bind(this);
        bean= (IndividualBean) getIntent().getSerializableExtra("register");
        isregist=getIntent().getStringExtra("what");
        initToolbar(R.string.companyauthentication);
        mToolbar.inflateMenu(R.menu.menu_regist_third);
        initEvent();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        iv_businesslicence_add.setOnClickListener(this);
        iv_identificationAdd.setOnClickListener(this);
        iv_taxAdd.setOnClickListener(this);
        iv_organizationcodeAdd.setOnClickListener(this);
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if ("regist".equals(isregist)) {
                    regist();
                } else {
                    certified();
                }
                return false;
            }
        });
    }

    /**
     * 认证
     */
    private void certified() {
        getTestApi().certifiedDistributors(SharePrefencesUtil.getFID(this), bean.getDistributor(),bean.getDistributorCode(), bean.getContractAmount(),
                bean.getContactor(), bean.getContactTel(), bean.getContactEmail(), businesslicence, identification, tax, organizationcode)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    /**
     * 注册
     */
    private void regist() {
        showLoading();
        getTestApi().individualRegist(bean.getLoginName(), bean.getPassword(), bean.getPhone(), bean.getCompanyName(),
                bean.getProvince(), bean.getCity(), bean.getArea(), bean.getAddress(), bean.getDistributor(),bean.getDistributorCode(), bean.getContractAmount(),
                bean.getContactor(), bean.getContactTel(), bean.getContactEmail(), businesslicence, identification, tax, organizationcode)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    Observer<BaseBean> observer=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            hideLoading();
            showToast(R.string.neterror);
            Log.e("error",e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean) {
            hideLoading();
            if(baseBean.getReturnNo().equals("1")){
                EventBus.getDefault().post(new MainEvent("registisover"));
                finish();
                showToast(baseBean.getReturnInfo());
                Log.e("info",baseBean.getReturnInfo());
            }else{
                showToast(baseBean.getReturnInfo());
            }
        }
    };
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == 1000) {
            if (data != null) {
                photos =
                        data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                if(what==1)
                {
                    iv_businesslicence_add.setImageBitmap(BitmapUtil.compressBitmap(photos.get(0)));
                }else if(what==2)
                {
                    iv_identificationAdd.setImageBitmap(BitmapUtil.compressBitmap(photos.get(0)));
                }else if(what==3)
                {
                    iv_taxAdd.setImageBitmap(BitmapUtil.compressBitmap(photos.get(0)));
                }else if(what==4)
                {
                    iv_organizationcodeAdd.setImageBitmap(BitmapUtil.compressBitmap(photos.get(0)));
                }
                new MyAsyncTask().execute();

            }
        }
    }
    /**
     * 生成该类的对象，并调用execute方法之后
     * 首先执行的是onProExecute方法
     * 其次执行doInBackgroup方法
     *
     */
    class MyAsyncTask extends AsyncTask<Integer, Integer, String> {


        public MyAsyncTask() {
            super();
        }


        /**
         * 这里的Integer参数对应AsyncTask中的第一个参数
         * 这里的String返回值对应AsyncTask的第三个参数
         * 该方法并不运行在UI线程当中，主要用于异步操作，所有在该方法中不能对UI当中的空间进行设置和修改
         * 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作
         */
        @Override
        protected String doInBackground(Integer... params) {
            Bitmap bitmap = BitmapFactory.decodeFile(photos.get(0));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);
            try
            {
                baos.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }

            byte[] buffer = baos.toByteArray();

            photo = Base64.encodeToString(buffer, 0, buffer.length, Base64.DEFAULT);
            return photo;
        }
        /**
         * 这里的String参数对应AsyncTask中的第三个参数（也就是接收doInBackground的返回值）
         * 在doInBackground方法执行结束之后在运行，并且运行在UI线程当中 可以对UI空间进行设置
         */
        @Override
        protected void onPostExecute(String result) {
            if(what==1)
            {
                businesslicence ="data:image/png;base64,"+photo;
            }else if(what==2)
            {
                identification ="data:image/png;base64,"+photo;
            }else if(what==3)
            {
                tax = "data:image/png;base64,"+photo;
            }else if(what==4)
            {
                organizationcode ="data:image/png;base64,"+photo;
            }
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {

            case R.id.iv_businesslicence_add:
                what=1;
                startChosePhoto(1000);
                break;
            case R.id.iv_identification_add:
                what=2;
                startChosePhoto(1000);
                break;
            case R.id.iv_tax_add:
                what=3;
                startChosePhoto(1000);
                break;
            case R.id.iv_organizationcode_add:
                what=4;
                startChosePhoto(1000);
                break;
        }
    }

    private void startChosePhoto(int what) {
        PhotoPickerIntent intent = new PhotoPickerIntent(this);
        intent.setPhotoCount(1);
        intent.setShowCamera(true);
        startActivityForResult(intent, what);
    }
}
